import React, { useEffect, useState } from 'react';
import {
  EditOutlined,
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import {
  Table,
  Tag,
  Row,
  Col,
  Input,
  Select,
  Button,
  Space,
  Tooltip,
  Modal,
  message,
  Drawer,
} from 'antd';
import { getResourcesList, deleteResource } from '@/services/menu';
import { Access } from 'umi';
import usePermission from '@/hooks/usePermission';
import styles from './style.less';
import MenuItem from './components/item';
import { createFromIconfontCN } from '@ant-design/icons';
import { useModel } from 'umi';

const { Option } = Select;
const { confirm } = Modal;
const Menu: React.FC = () => {
  const [name, setName] = useState<string>('');
  const [status, setStatus] = useState<number | null>(null);
  const [data, setData] = useState<MENU_API.Menu[]>();
  const [visible, setVisible] = useState<boolean>(false);
  const [menuInfo, setMenuInfo] = useState<MENU_API.Menu | undefined>(undefined);
  const [menuId, setMenuId] = useState<string | undefined>(undefined);
  const { initialState } = useModel('@@initialState');
  
  const MyIcon = createFromIconfontCN({
    scriptUrl: initialState?.sysSettings?.iconfontUrl,
  })


  const kindObj = {
    1: '菜单',
    2: '操作',
    3: '外部菜单',
    4: '目录',
    5: '按钮',
  };

  const fetchResourcesList = async (params: { name_cn?: string; status?: number }) => {
    const rsp = await getResourcesList(params);
    if (rsp.code === 0) {
      setData(rsp.data);
    }
  };

  useEffect(() => {
    fetchResourcesList({});
  }, []);

  const handleChangeName = (e: React.ChangeEvent<HTMLInputElement>) => {
    setName(e.target.value);
  };

  const handleChangeStatus = (value: number) => {
    setStatus(value);
  };

  const toSearch = () => {
    fetchResourcesList({ name_cn: name, status: status as number });
  };

  const reset = () => {
    setStatus(null);
    setName('');
  };

  const toDelete = (record: MENU_API.Menu) => {
    confirm({
      title: '是否确认删除选中菜单资源?',
      icon: <ExclamationCircleOutlined />,
      content: '',
      onOk: async () => {
        const rsp = await deleteResource({ id: record.id });
        if (rsp.code === 0) {
          message.success('删除成功');
          toSearch();
        }
      },
    });
  };

  const onClose = () => {
    setVisible(false);
    setMenuInfo(undefined);
  };

  const toAddOne = (id: string) => {
    setMenuId(id);
    setVisible(true);
  };

  const toEdit = (record: MENU_API.Menu) => {
    setMenuInfo(record);
    setVisible(true);
  };

  const toAdd = () => {
    setVisible(true);
  };

  const columns: COMMON_API.Columns[] = [
    {
      title: '名称',
      dataIndex: 'name_cn',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      align: 'center',
      width: 80,
      render: (text: string) =>  <MyIcon type={text}/>,
    },
    {
      title: '资源路径',
      dataIndex: 'path',
      align: 'center',
    },
    {
      title: '权限标识',
      dataIndex: 'perms',
      width: 120,
      align: 'center',
    },
    {
      title: '菜单类型',
      dataIndex: 'kind',
      width: 120,
      align: 'center',
      render: (text: number) => kindObj[text],
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 180,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text) => (text === 1 ? <Tag color="blue">启用</Tag> : <Tag>停用</Tag>),
      width: 100,
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'x',
      align: 'center',
      key: 'action',
      width: 180,
      render: (text, record) => (
        <Space>
          <Access accessible={usePermission('system:menu:add')} fallback={null}>
            <Tooltip title="新增">
            <Button
              type="primary"
              shape="circle"
              icon={<PlusOutlined />}
              onClick={() => toAddOne(record.id)}
            />
          </Tooltip>
          </Access>
          <Access accessible={usePermission('system:menu:update')} fallback={null}>
          <Tooltip title="修改">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => toEdit(record)}
            />
          </Tooltip>
          </Access>
          <Access accessible={usePermission('system:menu:delete')} fallback={null}>
          <Tooltip title="删除">
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => toDelete(record)}
            />
          </Tooltip>
          </Access>
        </Space>
      ),
    },
  ];

  return (
    <div className={styles.menuBox}>
      <div className={styles.searchBox}>
        <Row gutter={16}>
          <Col span={6}>
            <Row align="middle">
              <Col span={8}>菜单中文名称&nbsp;:</Col>
              <Col span={16}>
                <Input
                  value={name}
                  allowClear
                  placeholder="请输入菜单中文名称"
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => handleChangeName(e)}
                />
              </Col>
            </Row>
          </Col>
          <Col span={6}>
            <Row align="middle">
              <Col span={4}>状态&nbsp;:</Col>
              <Col span={16}>
                <Select
                  value={status}
                  placeholder="请选择状态"
                  allowClear
                  style={{ width: '100%' }}
                  onChange={handleChangeStatus}
                >
                  <Option value={1}>启用</Option>
                  <Option value={0}>停用</Option>
                </Select>
              </Col>
            </Row>
          </Col>
          <Col span={12} style={{ textAlign: 'right' }}>
            <Row align="middle">
              <Col span={24}>
                <Button onClick={reset} style={{ marginRight: '10px' }}>
                  重置
                </Button>
                <Button type="primary" onClick={toSearch}>
                  查询
                </Button>
              </Col>
            </Row>
          </Col>
        </Row>
      </div>
      <div className={styles.table}>
        <div className={styles.tableHeader}>
          <div className={styles.title}>菜单列表</div>
          <div className={styles.options}>
          <Access accessible={usePermission('system:menu:add')} fallback={null}>
          <Button type="primary" icon={<PlusOutlined />} onClick={toAdd}>
                新增
            </Button>
          </Access>
          </div>
        </div>
        <Table rowKey="id" columns={columns} dataSource={data} bordered pagination={false} />
      </div>

      <Drawer
        title={menuInfo ? '修改菜单资源' : '新增菜单资源'}
        placement="right"
        width={600}
        onClose={onClose}
        visible={visible}
      >
        {visible && (
          <MenuItem
            onClose={onClose}
            data={data}
            menuId={menuId}
            menuInfo={menuInfo}
            toFetchList={toSearch}
          />
        )}
      </Drawer>
    </div>
  );
};

export default Menu;
